/*
 * Copyright 2023 devaper
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.github.devaper.pigeon.request

import org.apache.commons.collections4.map.*

internal typealias RequestHeaders = CaseInsensitiveMap<String, MutableList<String>>

interface IRequestHeader {

    /**
     * 请求头
     */
    var requestHeaders: RequestHeaders

    /**
     * 请求头的Entry集合
     */
    val requestHeaderEntries: Set<Map.Entry<String, List<String>>>
        get() = requestHeaders.entries

    /**
     * @see getHeader
     */
    fun header(name: String) = getHeader(name)

    /**
     * @see setHeader
     */
    fun header(name: String, value: String) = setHeader(name, value)

    /**
     * 根据请求头名称获取其中的第一个值
     *
     * @param name 请求头名称
     * @return 请求头值
     */
    fun getHeader(name: String) = requestHeaders[name]?.firstOrNull()


    /**
     * 根据请求头名称获取所有的值
     *
     * @param name 请求头名称
     * @return 值列表
     */
    fun getHeaderValues(name: String) = requestHeaders[name]

    /**
     * 获取所有的请求头名称
     *
     * @return 请求头名称集合
     */
    fun getHeaderNames() = requestHeaders.keys

    /**
     * 设置请求头, 此方法会覆盖之前已有的请求头
     *
     * @param name 请求头名称
     * @param value 值
     */
    fun setHeader(name: String, value: String) {
        requestHeaders[name] = arrayListOf(value)
    }

    /**
     * 添加请求头
     *
     * @param name 请求头名称
     * @param value 值
     */
    fun addHeader(name: String, value: String) {
        requestHeaders.getOrPut(name) { ArrayList() }.add(value)
    }

    /**
     * 移除请求头
     *
     * @param name 请求头名称
     */
    fun removeHeader(name: String) {
        requestHeaders.remove(name)
    }

}